package com.yjf.demo.basic.user.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.yjf.demo.basic.user.controller.UserController;
import com.yjf.demo.basic.user.entity.User;
import com.yjf.demo.basic.user.mapper.UserMapper;
import com.yjf.demo.common.ResponseResult;
import com.yjf.demo.common.SessionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@RequiredArgsConstructor
public class UserService {

    private final SessionService sessionService;
    private final UserMapper userMapper;

    public ResponseResult<String> login(UserController.LoginParam loginParam) {
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, loginParam.username())
                .eq(User::getPassword, loginParam.password()));
        if (user == null) {
            return ResponseResult.loginErrorMsg("账号或者密码错误");
        }
        // 生成Token
        String sessionId = UUID.randomUUID().toString().replaceAll("-", "");

        //  存储到Redis
        sessionService.saveUserSession(sessionId, user);
        return ResponseResult.success(sessionId);
    }
}
